<?php


namespace catchAdmin\apipatient\controller;


use app\common\business\Node;
use app\common\business\Project;
use app\common\business\Question;
use app\common\lib\ZhyxMongo;
use app\common\model\BaseModel;
use app\common\model\NodeMiddle;
use app\Request;
use catchAdmin\propaganda\service\EdCenterService;
use catcher\base\CatchController;
use catcher\CatchResponse;
use catcher\exceptions\CatchException;
use catcher\exceptions\FailedException;
use catcher\exceptions\ValidateFailedException;

class NodeMessage extends CatchController
{
    public function pushContent(Request $request)
    {
        try {
            $userInfo = $request->userInfo;
            $answerInfo = $edList = [];
            $nodeId = $request->param("type", 0, "int");
            if (empty($nodeId)) {
                throw new ValidateFailedException("节点类型必须填写");
            }
            # 根据节点获取对应的随访问卷和宣教内容
            $condition[] = ["node_id", "=", $nodeId];
            $condition[] = ["deleted_at", "=", 0];
            $userDeptId = $userInfo["timeLine"][0]["deptId"] ?? 0;
            $nodeInfo = (new \app\common\model\Node())->where($condition)->where(function ($query) use ($userInfo, $userDeptId) {
                $query->whereOr([["apply_dept.dept_id", "=", (int)$userDeptId], ["is_whole_hospital", "=", 1]]);
            })->order("is_whole_hospital", "asc")->limit(1)->find();
            if (empty($nodeInfo)) {
                throw new FailedException("暂未设置该节点下的推送任务");
            }

            $mission = $nodeInfo["mission"] ?? [];

            $questionInfo = (new Project())->getProjectInfo($nodeInfo["project_id"]);

            # 生成问卷
            $answerId = (new Question())->createQuestion($userInfo, $questionInfo, ["creator_id" => 0, "username" => "系统", "creator_dept_id" => $userInfo["timeline"][0]["deptId"] ?? 0, 'creator_dept_name' => $userInfo["timeline"][0]["deptName"] ?? ""]);
            if (!empty($answerId)) {
                $answerInfo = [
                    'answer_id' => $answerId,
                    'projectId' => $nodeInfo["project_id"],
                    'project_name' => $questionInfo['name']
                ];
            }
            if ($nodeInfo["is_whole_hospital"] === 0 && empty($mission)) {
                # 查询一下是否存在全院性的表单
                $mission = (new \app\common\model\Node())->where($condition)->wehre([["is_whole_hospital", "=", 1]])->column("mission");
            }

            if (!empty($mission)) {
                # 执行宣教的推送
                $edList = (new EdCenterService())->pushBindEd($userInfo["patientId"], $mission);
            }

            $result = ZhyxMongo::getInstance()->setCollection('node_middle')->insertOne([
                'answerInfo' => $answerInfo,
                'edList' => $edList,
                'deleted_at' => 0,
                'created_at' => time()
            ]);
            if ($result->getInsertedId()) {
                $rst = (new NodeMiddle())->where("id", "=", (string)$result->getInsertedId())->find();

                return CatchResponse::success($rst);
            }
            return CatchResponse::fail("问卷创建失败");
        } catch (\Exception $exception) {
            throw new FailedException($exception->getMessage());
        }

    }


    public function getInfoByTaskId(string $taskId): \think\response\Json
    {
        $result = (new NodeMiddle())->where("id", "=", $taskId)->find();
        return CatchResponse::success($result);
    }
}